#include "Bistream.hpp"


int BitStream::ReadToEnd(){
    uint8_t* end = start + size - 1;
    if(p > end){
        return 0;
    }
    int8_t data_stop_one_bit = ReadU1();
    while(bits_left %8 != 0){
        uint8_t temp_data = ReadU1();
    }
    return 0;
}

bool BitStream::isFull(){
    if((p - start +1) == size){
        return true;
    }
    uint8_t* end = start+ size - 1;
    while(end > p && *end == 0){
        end--;
    }
    if(end > p){
        return false;
    }

    return false;
}


int BitStream::ReadU1(){
    int8_t res = 0;
    bits_left--;
    res = ((*p)>>bits_left) & 0x1;
    if(bits_left == 0){
        p++;
        bits_left = 8;
    }
    return res;
}


int BitStream::ReadU(int n){
    int res = 0;
    int i = 0;
    for(i = 0; i < n;i++){
        res |= (ReadU1() << (n-i-1));
    }
    return res;
}


int BitStream::ReadUE(){
    int res = 0;
    int i = 0;
    while((ReadU1()) == 0 &&(i < 32)){
        i++;  
    }         
    res = ReadU(i+1);
    return res - 1;
}

int BitStream::ReadSE(){
    int res = 0;
    int i = 0;
    while((ReadU1()) == 0 &&(i < 32)){
        i++;  
    }
    res = ReadU(i);
    if(ReadU1() == 1){
        return  -1*(res-1);
    }
    else{
        return res-1;
    }
}